<template>
	<view>
		<view class="cu-chat">
			<block v-for="(item, i) of messages" :key="i">
				<view class="cu-item self" v-if="item.from == user.userId">
					<view class="main">
						<view class="content bg-green shadow" v-if="item.msgType==0">
							<rich-text :nodes="getHtml(item)" style="word-break:break-all;"></rich-text>
						</view>
						<view class="shadow" v-if="item.msgType==1" @tap="previewImage(item.content)">
							<image  style="max-width: 450upx;" :lazy-load="true" mode="aspectFit" :src="item.content"></image>
						</view>
					</view>
					<view class="cu-avatar round" :style="'background-image:url(' + item.url + '),url(/static/img/none.jpg);'"></view>
					<view class="date">{{ dateUtils.formatL(item.createTime) }}</view>
				</view>
				<view class="cu-info round" v-if="item.extras.content != undefined">{{ item.extras.content }}</view>
				<view class="cu-item" v-if="item.from != user.userId">
					<view class="cu-avatar round" :style="'background-image:url(' + item.url + '),url(/static/img/none.jpg);'"></view>
					<view class="main">
						<view class="content shadow" v-if="item.msgType==0">
							<rich-text :nodes="getHtml(item)" style="word-break:break-all;"></rich-text>
						</view>
						<view class="shadow" v-if="item.msgType==1" @tap="previewImage(item.content)">
							<image  style="max-width: 450upx;" :lazy-load="true" mode="aspectFit" :src="item.content"></image>
						</view>
					</view>
					<view class="date">{{ dateUtils.formatL(item.createTime) }}</view>
				</view>
			</block>
		</view>
		<view style="bottom: 0;position: fixed;">
			<view class="cu-bar input" style="background-color:#eee">
				<view class="action"><text :class="cuIconRoundadd" @touchstart="showIcon"></text></view>
				<textarea
					auto-height="true"
					class="bg-white phoneNumber radius uni-input"
					fixed
					style="max-width: 450upx;min-height: 65upx;"
					confirm-type="发送"
					v-model="content"
					maxlength="300"
					cursor-spacing="10"
				/>
				<view class="action"><text :class="cuIconEmojifill" @touchstart="showEmj"></text></view>
				<button class="cu-btn bg-green shadow" @touchstart="send()" v-no-more-click :disabled="$store.state.disabled">发送</button>
			</view>
			<view class="uni-flex uni-column">
				<view v-show="isShowEmj">
					<emotion @emotion="handleEmj" style="width:100%;height:380upx;background-color:#eee"></emotion>
				</view>
				<view v-show="isShowIcon">
					<cmd-swiper @clickHandler="clickHandler" :cuIcon="cuIcon" style="width:100%;height:380upx;background-color:#eee" v-show="isShowIcon"></cmd-swiper>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import emotion from '@/components/bkhumor-emoji/index.vue';
import cmdSwiper from '@/components/cmd-swiper/cmd-swiper.vue';
export default {
	components: {
		emotion,
		cmdSwiper
	},
	data() {
		return {
			messages: [],
			user: {},
			friend: {},
			friendId: '',
			content: '',
			isShowEmj: false,
			isShowIcon: false,
			cuIconEmojifill: 'cuIcon-emojifill text-gray',
			cuIconRoundadd: 'cuIcon-roundadd text-gray',
			cuIcon: [
				{
					name: 'location',
					text: '地图',
					isShow: true
				},
				{
					name: 'pic',
					text: '图片',
					isShow: true
				},
				{
					name: 'record',
					text: '视频直播',
					isShow: true
				},
				{
					name: 'record',
					text: '视频通话',
					isShow: true
				}
			]
		};
	},
	onLoad(option) {
		if (option.params) {
			var params = JSON.parse(decodeURIComponent(option.params));
			this.friend = params;
			this.user = this.$store.state.userInfo;
			this.friendId = params.from == this.user.userId ? params.to : params.from;
			this.$store.state.currentRoom.id = params.group_id;
			uni.setNavigationBarTitle({
				title: params.friendNickName
			});
		}
		this.onRefresh();
	},
	onHide() {
		this.$store.state.currentRoom.id = '';
		this.$store.state.currentRoom.onMessage = false;
	},
	onShow() {
		this.$store.state.currentRoom.id = this.friend.group_id;
		//下拉到底部
		this.$nextTick(function() {
			uni.pageScrollTo({
				scrollTop: 999999999
			});
		});
	},
	watch: {
		'$store.state.currentRoom.onMessage': {
			handler(val, old) {
				if (!val) return;
				this.onRefresh();
				this.$store.state.currentRoom.onMessage = false;
			},
			immediate: true
		}
	},
	methods: {
		onRefresh() {
			console.log('chat onRefresh');
			// #ifndef  H5
			let selectLastTime = '0';
			if (this.messages.length > 0) {
				selectLastTime = this.messages[this.messages.length - 1].createTime;
			}
			let sql = 'SELECT a.* FROM "message" a   WHERE "group_id"=\'{0}\'  and "createTime">\'{1}\' ORDER BY createTime DESC LIMIT 100'.format(
				this.$store.state.currentRoom.id,
				selectLastTime
			);
			this.db.selectSQL(
				sql,
				function(datas) {
					datas.reverse();
					for (let data of datas) {
						data.extras = JSON.parse(data.extras);
						data.url = this.getImgUrl('user', data.from);
						this.messages.push(data);
					}
					this.$nextTick(function() {
						uni.pageScrollTo({
							scrollTop: 999999999
						});
					});
					console.log(JSON.stringify(this.messages), 'messages');
				}.bind(this)
			);
			let insertIndex = "update 'index' set count=0 where group_id='{0}'".format(this.$store.state.currentRoom.id);
			this.db.executeSQL(insertIndex);
			// #endif
			// #ifdef  H5
			this.messages = [
				{
					id: '32-1584515460010',
					chatType: 2,
					cmd: 11,
					msgType: 1,
					content: 'http://122.51.141.95:8762/image/user/32.png',
					createTime: '1584515460010',
					from: '32',
					to: '37',
					group_id: '37-32',
					extras: {},
					isRead: 0,
					url: 'http://122.51.141.95:8762/image/user/32.png'
				},
				{
					id: '32-1584515624831',
					chatType: 2,
					cmd: 11,
					msgType: 0,
					content: '<p>4444444444444444444444<img src="http://122.51.141.95:8762/image/emoji/14.gif" alt="表情"></img>3333</p><p>66666666666</p>',
					createTime: '1584515624831',
					from: '32',
					to: '37',
					group_id: '37-32',
					extras: {},
					isRead: 0,
					url: 'http://122.51.141.95:8762/image/user/32.png'
				}
			];
			// #endif
		},
		previewImage(url){
			 // 预览图片
			uni.previewImage({
				urls: [url]
			});
		},
		//图片路径替换
		getHtml(item) {
			if(item.msgType!=0){
				return item.content;
			}
			return this.GLOBAL.convert.toHtml(item.content).replace(/<img(.*?)src="(.*?)"(.*?)>/g,`<img$1src="${this.$store.state.imgUrl}/emoji/$2"$3>`);
		},
		clickHandler(item) {
			console.log(item.text, 'clickHandler');
			if (item.text == '地图') {
				let users = {};
				users[this.user.userId] = { id: this.user.userId.toString(), name: this.user.userNikename };
				users[this.friendId] = { id: this.friendId, name: this.friend.friendNickName };
				var params = encodeURIComponent(JSON.stringify(users));
				uni.navigateTo({
					url: '/pages/map/map?params=' + params
				});
			}
			if (item.text == '图片') {
				this.insertImage();
			}
			if (item.text == '视频直播') {
				let users = [];
				users.push({ id: this.friendId, name: this.friend.friendNickName });
				var params = encodeURIComponent(JSON.stringify(users));
				uni.navigateTo({
					url: '/pages/video/live?params=' + params
				});
			}
			if (item.text == '视频通话') {
				let users = { id: this.user.userId.toString(),friendId:this.friendId };
				var params = encodeURIComponent(JSON.stringify(users));
				uni.navigateTo({
					url: '/pages/video/call?params=' + params
				});
			}
		},
		handleEmj(emoji) {
			console.log(emoji);
			if (emoji.text == '删除') {
				//匹配最后一个表情符号并删除。
				this.content = this.content.replace(/\[.{1,5}\]$/, '');
			} else {
				this.content += this.GLOBAL.convert.toText(emoji.code);
			}
		},
		showEmj() {
			if (this.isShowIcon) {
				this.showIcon();
			}
			let bool = !this.isShowEmj;
			if (bool) {
				this.cuIconEmojifill = 'cuIcon-emojifill text-blue';
			} else {
				this.cuIconEmojifill = 'cuIcon-emojifill text-gray';
			}
			this.isShowEmj = bool;
		},
		showIcon() {
			if (this.isShowEmj) {
				this.showEmj();
			}
			let bool = !this.isShowIcon;
			if (bool) {
				this.cuIconRoundadd = 'cuIcon-roundadd text-blue';
			} else {
				this.cuIconRoundadd = 'cuIcon-roundadd text-gray';
			}
			this.isShowIcon = bool;
		},
		insertImage() {
			uni.chooseImage({
				count: 1,
				success: res => {
					let id = `${this.user.userId}_${new Date().getTime()}`;
					let imgUrl = this.getImgUrl('chatImg', id);
					uni.uploadFile({
						url: this.$store.state.baseUrl + '/user-admin/file/upload',
						filePath: res.tempFilePaths[0],
						name: 'file',
						fileType: 'image',
						formData: { id: id, type: 'chatImg' },
						header: {
							token: uni.getStorageSync(this.GLOBAL.CacheKeys.token)
						},
						success: uploadFileRes => {
							console.log(uploadFileRes.data);
							let res = JSON.parse(uploadFileRes.data);
							if (res.code != '200') {
								uni.showModal({
									content: '图片发送失败',
									showCancel: false
								});
							} else {
								let msg = {
									from: this.user.userId.toString(),
									to: this.friendId,
									cmd: 11,
									createTime: new Date().getTime(),
									msgType: 1, //图片
									chatType: 2, //0:系统消息,1:公聊,2:私聊
									content: imgUrl,
									extras: {}
								};
								this.sendMsg(msg);
							}
						}
					});
				}
			});
		},
		sendMsg(msg) {
			let app = getApp();
			this.$store.state.currentRoom.onMessage = false;
			this.ws.socketTask.send({
				data: JSON.stringify(msg), //将json对象转换成字符串,
				success: async () => {
					console.log('socket send success');
					msg.id = msg.from + '-' + msg.createTime;
					msg.group_id = this.$store.state.currentRoom.id;
					msg.userId = this.user.userId.toString();
					// #ifndef  H5
					await app.insertMsg(msg, this);
					// #endif
					this.$store.state.currentRoom.onMessage = true;
					this.content = '';
					if (this.isShowEmj) {
						this.showEmj();
					}
				},
				fail: () => {
					console.log('socket send fail');
					uni.showModal({
						title: '发送失败',
						content: '请检查网络环境',
						showCancel: false
					});
				}
			});
		},
		send() {
			if (this.content.trim().length == 0) return;
			let msg = {
				from: this.user.userId.toString(),
				to: this.friendId,
				cmd: 11,
				createTime: new Date().getTime(),
				msgType: 0,
				chatType: 2, //0:系统消息,1:公聊,2:私聊
				content: this.content,
				extras: {}
			};
			this.sendMsg(msg);
		}
	}
};
</script>

<style>
page {
	padding-bottom: 100upx;
}
.phoneNumber {
	font-size: 0.8rem;
	display: inline-block;
	-moz-box-sizing: border-box;
	box-sizing: border-box;
	font-family: PingFang-SC-Regular;
	border: 1upx solid #68be4c;
	border-radius: 0.1rem;
	text-indent: 0.1rem;
	color: #333;
	padding: 0.16rem 0;
	float: left;
}
</style>
